const app = getApp();
const _requsetCYZ = require('../../../utils/requestData');
const _functionCYZ = require('../../../utils/common');
const QQMapWX = require('../../../utils/qqmap-wx-jssdk.min');// 引入SDK核心类
Page({
    data: {
        this_shop_id: 0,
        this_fendian_id:0,
        this_config_op: null,
        this_shop_info_c: null, //独立商城配置
        this_shop_config: null,
        this_select_cate_id: 0,
        this_shop_data: null,
        this_cate_goods_data: null,
        this_login_user_id: 0,
        is_show_gloading: true,
        is_show_share_quan:0,
        show_share_quan_info:'',
        this_data_share_title: '',
        this_data_share_desc: '',
        this_data_share_img: '',
        this_isshare_timeline:false
    },
    //搜索
    inputTyping: function (e) {
        var that = this;
        wx.navigateTo({
            url: "../category/index?s_keyword=" + e.detail.value + "&shop_id=" + that.data.this_shop_id
        });
    },
    changeCate: function (e) {
        this.setData({
            this_select_cate_id: e.currentTarget.dataset.cate_id
        });
        this.get_cate_goods_data();
    },
    onLoad: function (op) {
        var that = this;
        let lau_option = wx.getLaunchOptionsSync();
        if(lau_option.scene == 1154){//分享朋友圈
            that.setData({this_isshare_timeline:true});
        }else{
            that.setData({this_isshare_timeline:false});
        }
        let _this = this,scene = app.getSceneData(op);
        that.setData({
            this_config_op: op,
            this_fendian_id:scene.fendian_id || 0
		});
		if(!that.data.this_isshare_timeline){
            that.getLocation();
        }else{
            that.get_index_data();
        }
	},
	//获取用户位置信息
    getLocation: function () {
        const that = this;
        let qqmakSdk = null;
        _requsetCYZ.cyz_requestGet('/ShopApi/getShopQQMapKeyV2', {}, function (res) {
            if(res.info.is_get_location == 1){
                _functionCYZ.CYZ_loading("定位中，请稍候...");
                wx.getLocation({
                    type: 'wgs84',
                    success: function (res) {
						console.log(res)
                        wx.setStorageSync('global_u_lat', res.latitude || 0);
                        wx.setStorageSync('global_u_lng', res.longitude || 0);
                        wx.setStorageSync('global_u_address', '');
                        that.addFenxiaoAction();
                        // qqmakSdk.reverseGeocoder({
                        //     location: {
                        //         latitude: res.latitude,
                        //         longitude: res.longitude
                        //     },
                        //     success: (res) => {
                        //         wx.setStorageSync('global_u_lat', res.result.location.lat || 0);
                        //         wx.setStorageSync('global_u_lng', res.result.location.lng || 0);
                        //         wx.setStorageSync('global_u_address', res.result.address || '');
                        //         that.addFenxiaoAction();
                        //     },
                        //     fail:(res)=>{
                        //         that.addFenxiaoAction();
                        //     }
                        // });
                    },
                    fail: function () {
                        that.addFenxiaoAction();
                    }
                })
            }else{
                that.addFenxiaoAction();
            }
        });
	},
	//绑定分销关系
    addFenxiaoAction:function(){
        const that = this;
        let op = that.data.this_config_op;
        if(!that.data.this_isshare_timeline){
            if (op.scene != undefined) {
                let scene = decodeURIComponent(op.scene);
                if (op.scene > 0) {
                    var requestData = {};
                    requestData.top_user_id = scene || 0;
                    _requsetCYZ.cyz_requestGet('/ShopApi/addFenxiaoUser', requestData, function (cyz_data) {
                        wx.hideToast();
                        if (cyz_data.code == 1) {
                            that.get_index_data();
                        } else if (cyz_data.code == 2) {
                            app.getUserDataToken(function (token) {
                                that.addFenxiaoAction();
                            });
                            return false;
                        }
                    });
                }else{
                    that.get_index_data();
                }
            } else if (op.tg_user_id != undefined) {
                if (op.tg_user_id > 0) {
                    var requestData = {};
                    requestData.top_user_id = op.tg_user_id || 0;
                    _requsetCYZ.cyz_requestGet('/ShopApi/addFenxiaoUser', requestData, function (cyz_data) {
                        wx.hideToast();
                        if (cyz_data.code == 1) {
                            that.get_index_data();
                        } else if (cyz_data.code == 2) {
                            app.getUserDataToken(function (token) {
                                that.addFenxiaoAction();
                            });
                            return false;
                        }
                    });
                }else{
                    that.get_index_data();
                }
            } else {
                that.get_index_data();
            }
        }else{
            that.get_index_data();
        }
    },
    get_index_data: function () {
		console.log('---------------')
        var that = this;
        _functionCYZ.CYZ_loading();
        var requestData = {};
        requestData.shop_id = that.data.this_shop_id;
        requestData.fendian_id = that.data.this_fendian_id;
        if(that.data.this_isshare_timeline == true){
            requestData.no_check_login = 1;
        }else{
            requestData.no_check_login = 0;
        }
        _requsetCYZ.cyz_requestGet('/ShopApi/getShopInfo', requestData, function (cyz_data) {
            wx.hideToast();
            if (cyz_data.code == 1) {
                that.setData({
                    this_shop_config: cyz_data.info.shop_config,
                    this_shop_data: cyz_data.info,
                    this_login_user_id: cyz_data.info.login_user_id,
                    this_shop_info_c: cyz_data.info.shop_info_c,
                    this_select_cate_id: cyz_data.info.select_cate_id,
                    is_show_gloading: false,
                    this_data_share_title: cyz_data.info.shop_config.shop_name,
                    live_info: cyz_data.info.live_info,
                    is_show_share_quan:cyz_data.info.is_show_share_quan,
                    show_share_quan_info:cyz_data.info.show_share_quan_info
                });
                wx.setNavigationBarTitle({
                    title: cyz_data.info.shop_info_c?cyz_data.info.shop_info_c.shop_title : '商城'
                });
                that.get_cate_goods_data();
                that.getShareData();
            } else if (cyz_data.code == 2) {
                app.getUserDataToken(function (token) {
                    that.get_index_data();
                });
                return false;
            }
        });
    },
    get_cate_goods_data: function () {
        //请求分类商品
        var that = this;
        _functionCYZ.CYZ_loading();
        _requsetCYZ.cyz_requestGet('/ShopApi/getIndexCateGoods', {
            cate_id: that.data.this_select_cate_id,
            fendian_id:that.data.this_fendian_id
        }, function (cyz_data) {
            wx.hideToast();
            if (cyz_data.code == 1) {
                that.setData({
                    this_cate_goods_data: cyz_data.info
                });
            }
        });
    },
    //链接跳转
    go_url_bind: function (e) {
        wx.navigateTo({
            url: e.currentTarget.dataset.url
        });
    },
    go_shop_cart_bind: function (e) {
        var that = this;
        wx.navigateTo({
            url: "../cart/index?shop_id=" + that.data.this_shop_id
        });
    },
    //商品列表跳转
    go_goods_list_bind: function (e) {
        var that = this;
        wx.navigateTo({
            url: "../category/index?cid=" + e.currentTarget.id + "&shop_id=" + that.data.this_shop_id
        });
    },
    //商品详情跳转
    go_goods_info_bind: function (e) {
        wx.navigateTo({
            url: '../detail/index?goods_id=' + e.currentTarget.id
        });
    },
    //公用页面跳转
    go_base_url_bind: function (e) {
        let t_url = e.currentTarget.dataset.url;
        wx.navigateTo({
            url: t_url
        });
    },
    go_show_app_bind:function(){
        let _this = this;
        wx.navigateToMiniProgram({
            appId: _this.data.this_shop_config.show_app_appid,
        })
    },
    go_shop_home_bind: function () {
        wx.switchTab({
            url: '../../business/index'
        })
    },
    go_share_home_bind: function () {
        wx.showShareMenu();
    },
    /**
     * 跳转页面
     */
    onAppNavigateTap: function (e) {
        const dataset = e.detail.target ? e.detail.target.dataset : e.currentTarget.dataset;
        const url = dataset.url,
            appurl = dataset.appurl,
            atype = dataset.atype || 1,
            appId = dataset.appid;
        if (atype == 1) {
            wx.navigateTo({
                url: url,
                fail: () => {
                    wx.switchTab({
                        url: url,
                    });
                }
            });
        } else if (atype == 2) {
            wx.navigateToMiniProgram({
                appId: appId,
                path: appurl
            });
        }
    },
    //领取优惠券
    quan_lingqu_bind: function (e) {
        var that = this;
        let qid = e.currentTarget.id;
        _functionCYZ.CYZ_loading();
        var requestData = {};
        requestData.qid = qid;
        requestData.shop_id = that.data.this_shop_id;
        _requsetCYZ.cyz_requestGet('/ShopApi/ShopQuanLingqu', requestData, function (xyz_data) {
            wx.hideToast();
            if (xyz_data.code == 2) {
                app.getUserDataToken(function (token) {
                    that.quan_lingqu_bind(e);
                });
            } else if (xyz_data.code == 1) {
                wx.showModal({
                    title: '提示',
                    content: "领取优惠券成功",
                    showCancel: false,
                    success: function (res) {
                        that.get_index_data();
                    }
                });

            } else {
                _functionCYZ.CYZ_alert(xyz_data.info);
                return false;
            }
        });
    },
    share_quan_lingqu_action(){
      var that = this;
      _functionCYZ.CYZ_loading();
      var requestData = {};
      _requsetCYZ.cyz_requestGet('/ShopApi/ShopQuanShareLingqu', requestData, function (xyz_data) {
          wx.hideToast();
          if (xyz_data.code == 2) {
              app.getUserDataToken(function (token) {
                  that.share_quan_lingqu_action();
              });
          } else{
              wx.showModal({
                  title: '提示',
                  content: xyz_data.info,
                  showCancel: false,
                  success: function (res) {
                      that.get_index_data();
                  }
              });
          }
      });
    },
    onPullDownRefresh: function () {
        var that = this;
        that.get_index_data();
        setTimeout(() => {
            wx.stopPullDownRefresh()
        }, 1000);
    },

    getShareData: function () {
        var that = this;
        var requestData = {};
        _requsetCYZ.cyz_requestGet('/HsgShareApi/index', requestData, function (xyz_data) {
            if (xyz_data.info != null) {
                if (xyz_data.info.share_title != '') {
                    that.setData({
                        this_data_share_title: xyz_data.info.share_title
                    });
                }
                if (xyz_data.info.share_desc != '') {
                    that.setData({
                        this_data_share_desc: xyz_data.info.share_desc
                    });
                }
                if (xyz_data.info.share_img != '') {
                    that.setData({
                        this_data_share_img: xyz_data.info.share_img
                    });
                }
            }
        });
    },
    onShareAppMessage: function () {
        var that = this;
        var sharePath = 'pages/shop/shop_index/index?shop_id=' + that.data.this_shop_id + '&tg_user_id=' + that.data.this_login_user_id;
        return {
            title: that.data.this_data_share_title,
            desc: that.data.this_data_share_desc,
            path: sharePath,
            imageUrl: that.data.this_data_share_img
        }
    },
    onShareTimeline:function(){
        let that = this;
        return {
            title: that.data.this_data_share_title,
            query: 'shop_id=' + that.data.this_shop_id + '&tg_user_id=' + that.data.this_login_user_id,
            imageUrl: ''
        }
    },

    // 跳转直播间
    gotoLive: function () {
        // 填写具体的房间号，可通过下面【获取直播房间列表】 API 获取
        let roomId = [this.data.live_info.room_id];
        // 开发者在直播间页面路径上携带自定义参数（如示例中的path和pid参数），后续可以在分享卡片链接和跳转至商详页时获取，详见【获取自定义参数】、【直播间到商详页面携带参数】章节（上限600个字符，超过部分会被截断）
        let customParams = encodeURIComponent(JSON.stringify({
            path: 'pages/index/index',
        }))
        wx.navigateTo({
            url: `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${roomId}&custom_params=${customParams}`
        })
    },
})
